package com.example.sensors;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.os.Handler;
import android.util.SparseIntArray;

import com.example.MyAudioManager;

public class Sensor_Audio extends AbstractSensor {

	public static final String NAME = "AUDIO";

	private static MyAudioManager audioManager = null;

	private final Handler mHandler = new Handler();
	private static SparseIntArray hm;
	private static SparseIntArray hm2;

	public Sensor_Audio() {
		audioManager = MyAudioManager.getInstance();

		hm = getVolumes();
		updateSensorData();
	}

	private final Runnable mUpdateTimeTask = new Runnable() {
		public void run() {
			updateSensorData();
			mHandler.postDelayed(mUpdateTimeTask, 10000);
		}
	};

	private SparseIntArray getVolumes() {
		SparseIntArray hm = new SparseIntArray();
		MyAudioManager.getInstance();
		Iterator<Entry<String, Integer>> iterator = MyAudioManager
				.getConstants().entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Integer> current = iterator.next();
			hm.put(current.getValue(),
					audioManager.getVolume(current.getValue()));
		}
		return hm;
	}

	public void updateSensorData() {
		hm2 = getVolumes();
		for (int i = 0; i < hm2.size(); i++) {
			int key = hm2.keyAt(i);
			int value = hm2.get(key);
			if (hm.get(key) != value) {
				Map<String, Object> eventArgs = initEventArgs();
				eventArgs.put("eventType", "sensorInfoReceived");
				eventArgs.put("streamType", "" + key);
				eventArgs.put("volume", "" + value);
				OnSensorChanged(eventArgs);
				hm.put(key, value);
			}
		}
	}

	@Override
	public void setSensorParameters(Map<String, Object> parameters) {
		super.setSensorParameters(parameters);
		setVolume((Integer) parameters.get("streamType"),
				(Integer) parameters.get("volume"));
	}

	public void setVolume(int stream_type, int volume) {
		volume = audioManager.setVolume(stream_type, volume);
		hm.put(stream_type, volume);
		updateSensorData();
	}

	public void disableSensor() {
		super.disableSensor();
	}

	public void enableSensor() {
		super.enableSensor();
	}

	public String getSensorName() {
		return NAME;
	}
}
